/**
 * 作者：致心 vue项目所有文件命名全部采用中划线分隔   fileUtils
 * 创建时间：2021/2/19 13:19
 */

const path = require('path');
const fs = require('fs');
let collectObj = {
    filesList: [],
    dirsList: []
};

function readFileList(dir, collectObj) {
    let {
        filesList,
        dirsList,
    } = collectObj
    const files = fs.readdirSync(dir);
    files.forEach((item, index) => {
        const fullPath = path.join(dir, item);
        const stat = fs.statSync(fullPath);
        if (stat.isDirectory()) {
            dirsList.push(fullPath);
            readFileList(path.join(dir, item), collectObj); //递归读取文件
        } else {

            filesList.push(fullPath);
        }
    });
    return collectObj;

}

module.exports = {
    /**
     * @Description :读取文件夹下面所有文件和文件夹
     * @Author :致心
     * @Date :2021/2/19 13:28
     * @param dir {string}
     * @returns {{dirsList: [], filesList: []}}
     */
    readFileList: (dir) => {
        return readFileList(dir, collectObj)
    },

    /**
     * @Description :
     * @Author :致心
     * @Date :2021/2/19 13:44
     * @param {*} path 必传参数可以是文件夹可以是文件
     * @param {*} reservePath 保存path目录 path值与reservePath值一样就保存
     */
    delFile: function (path, reservePath) {
        if (fs.existsSync(path)) {
            if (fs.statSync(path).isDirectory()) {
                let files = fs.readdirSync(path);
                files.forEach((file, index) => {
                    let currentPath = path + "/" + file;
                    if (fs.statSync(currentPath).isDirectory()) {
                        delFile(currentPath, reservePath);
                    } else {
                        fs.unlinkSync(currentPath);
                    }
                });
                if (path !== reservePath) {
                    fs.rmdirSync(path);
                }
            } else {
                fs.unlinkSync(path);
            }
        }
    }
}
